﻿
using AiMoBridge.Interface;
using AiMoRhino.ScriptInstance.LinkSelect;
using Rhino;
using System;
using System.Collections;

namespace AiMoCore
{
    public abstract partial class CSharpScriptInstance : IDisposable
    {
        Linker SelLinker { get; }
        public CSharpScriptInstance()
        {
            SelLinker = new Linker();
            try
            {
                OnLoad();
            }
            catch (Exception ex)
            {
                RhinoApp.WriteLine("警告：载入时OnLoad()代码运行出错：\n" + ex.ToString());
            }
        }

        public void Dispose()
        {
            SelLinker.Dispose();
            LoopOff();
            previewer.ClosePreview();
        }


        public void BeforeMain()
        {
            SelLinker.ResetGetOrder();
        }

        /// <summary>
        /// Override 这个函数，以在命令载入时只运行一次
        /// </summary>
        public virtual void OnLoad()
        {
        }
        ///// <summary>
        ///// 这个值指向是否需要运行在UI主线程。由编译时指定，默认不运行
        ///// </summary>
        //public virtual bool RunningInUIThread => false;

        public abstract void Main();

        #region Print
        public void Print(string text)
        {
            ToDebugPrint(text);
        }

        public void Print(string content, params object[] args)
        {
            ToDebugPrint(string.Format(content, args));
        }

        public void Print(object obj)
        {
            if (obj == null) ToDebugPrint("null");
            else if (obj is IEnumerable iEnumerable)
            {
                string name = iEnumerable.GetType().Name;
                name = name.Substring(0, name.Length - 2);

                string content = $"{name}" + " { ";
                int count = 0;
                foreach (object obj2 in iEnumerable)
                {
                    if (count == 0)
                    {
                        content += obj2.ToString();
                    }
                    else if (count < 10)
                    {
                        content += ", " + obj2.ToString();
                    }
                    else if (count == 10)
                    {
                        content += $", ......";
                    }
                    count++;
                }
                content += " } " + $" ({count})";
                ToDebugPrint(content);
            }
            else if (obj is string ss)
            {
                ToDebugPrint(ss);
            }
            else ToDebugPrint($"[{obj.GetType()}] {obj}");
        }

        void ToDebugPrint(string text)
        {
            if (OnLoop || debugPrinter == null)
            {
                RhinoApp.WriteLine("[AiMo Debug] " + text);
            }
            else debugPrinter.PrintDebug(text);
        }

        IDebugPrinter debugPrinter;
        internal void SetPrinter(IDebugPrinter printer)
        {
            debugPrinter = printer;
        }
        #endregion


    }
}
